(function ($) {
    $.fn.customMultiselect = function (options) {
        const settings = $.extend(
            {
                placeholder: "请选择",
                options: [],
                selected: [],
                keepSelectionOrder: true, // 新增选项，默认为true
                disabled: false // 添加禁用选项，默认为false
            },
            options
        );

        return this.each(function () {
            const $container = $(this);
            let isOpen = false;

            // 创建DOM结构
            const $summary = $('<div class="multiselect-summary"></div>');
            const $dropdown = $('<div class="multiselect-dropdown"></div>');

            $container.addClass("custom-multiselect");
            $container.append($summary);
            $container.append($dropdown);
            
            // 应用初始禁用状态
            if (settings.disabled) {
                $container.addClass("disabled");
                $summary.addClass("disabled");
            }

            // 初始化选项
            settings.options.forEach((option) => {
                const isSelected = settings.selected.includes(option.value);
                const isDisabled = option.disabled || false;
                // 添加自定义data属性
                let dataAttributes = '';
                if (option.data) {
                    for (const key in option.data) {
                        dataAttributes += ` data-${key}="${option.data[key]}"`;
                    }
                }
                const $option = $(`
                  <div class="multiselect-option" data-value="${option.value}"${dataAttributes}>
                      <label class="multiselect-label">
                          <input type="checkbox" class="multiselect-checkbox" 
                              ${isSelected ? "checked" : ""}
                              ${isDisabled ? "disabled" : ""}>
                          <span class="multiselect-custom-checkbox"></span>
                          ${option.text}
                      </label>
                  </div>
              `);
                if (isDisabled) {
                    $option.addClass("disabled");
                }
                $dropdown.append($option);
            });

            // 更新摘要显示
            function updateSummary() {
                const selectedOptions = [];
                const selectionOrder = [];

                // 记录选中顺序
                $dropdown.find(".multiselect-option").each(function () {
                    const $option = $(this);
                    if ($option.find(".multiselect-checkbox").is(":checked")) {
                        selectionOrder.push({
                            text: $option.text().trim(),
                            value: $option.data("value"),
                            timestamp: $option.data("selected-time") || 0,
                        });
                    }
                });

                // 按选择时间排序
                selectionOrder.sort((a, b) => a.timestamp - b.timestamp);

                $summary.empty();

                if (selectionOrder.length === 0) {
                    $summary.text(settings.placeholder).addClass("placeholder");
                } else {
                    $summary.removeClass("placeholder");
                    $summary.text(selectionOrder.map((opt) => opt.text).join(", "));
                }
            }

            $container.data('updateSummary', function() {
                updateSummary();
            });
            // 初始化
            updateSummary();

            // 点击摘要切换下拉框
            $summary.on("click", function (e) {
                e.stopPropagation();
                // 如果组件被禁用，则不响应点击
                if ($container.hasClass("disabled")) {
                    return;
                }
                isOpen = !isOpen;
                $dropdown.toggle(isOpen);
                $summary.toggleClass("open", isOpen);
            });

            // 点击选项切换选中状态
            $dropdown.on("click", ".multiselect-option", function (e) {
                // 如果点击的是checkbox，则跳过父元素处理
                if ($(e.target).hasClass('multiselect-checkbox')) {
                    return;
                }

                // 添加禁用检查
                if ($(this).hasClass("disabled")) {
                    return;
                }
                // 触发自定义点击事件
                $container.trigger("multiselect.optionClick", {
                    element: $(this),
                    value: $(this).data("value"),
                    data: $(this).data()
                });

                const $checkbox = $(this).find(".multiselect-checkbox");
                const isChecked = !$checkbox.prop("checked");
                $checkbox.prop("checked", isChecked);

                if (isChecked) {
                    $(this).data("selected-time", Date.now());
                    // 记录当前点击的值
                    $container.data("last-clicked-value", $(this).data("value"));
                } else {
                    // 取消选中时清除记录
                    $container.data("last-clicked-value", null);
                }

                updateSummary();
                // 添加change事件触发
                $(this).trigger('option.click');
                $container.trigger("change");
            });

            // 单独处理checkbox点击事件
            $dropdown.on("click", ".multiselect-checkbox, .multiselect-custom-checkbox", function (e) {
                e.stopPropagation();
                const $checkbox = $(this).hasClass('multiselect-custom-checkbox') 
                    ? $(this).siblings('.multiselect-checkbox')
                    : $(this);
                const $option = $checkbox.closest(".multiselect-option");

                if ($option.hasClass("disabled")) {
                    return;
                }

                // 切换选中状态
                const isChecked = !$checkbox.prop("checked");
                $checkbox.prop("checked", isChecked);

                $container.trigger("multiselect.optionClick", {
                    element: $option,
                    value: $option.data("value"),
                    data: $option.data()
                });

                if (isChecked) {
                    $option.data("selected-time", Date.now());
                    $container.data("last-clicked-value", $option.data("value"));
                } else {
                    $container.data("last-clicked-value", null);
                }

                updateSummary();
                $option.trigger('option.click');
                $container.trigger("change");
            });

            // 修改获取当前点击值的方法
            $container.data("getCurrentValue", function () {
                const lastClicked = $container.data("last-clicked-value");
                // 检查该值是否仍处于选中状态
                if (
                    lastClicked &&
                    $dropdown.find(
                        `.multiselect-option[data-value="${lastClicked}"] .multiselect-checkbox:checked`
                    ).length > 0
                ) {
                    return lastClicked;
                }
                return null;
            });

            // 点击其他地方关闭下拉框
            $(document).on("click", function () {
                if (isOpen) {
                    isOpen = false;
                    $dropdown.hide();
                    $summary.removeClass("open");
                    // 触发自定义隐藏事件
                    $container.trigger("multiselect.hide");
                }
            });

            // 阻止下拉框点击事件冒泡
            $dropdown.on("click", function (e) {
                e.stopPropagation();
            });

            // 获取选中值的方法
            $container.data("getSelectedValues", function () {
                const selectedValues = [];
                const $checked = $dropdown.find(".multiselect-checkbox:checked");

                if (settings.keepSelectionOrder) {
                    // 按选中顺序获取值
                    const selectionOrder = [];
                    $dropdown.find(".multiselect-option").each(function () {
                        const $option = $(this);
                        if ($option.find(".multiselect-checkbox").is(":checked")) {
                            selectionOrder.push({
                                value: $option.data("value"),
                                timestamp: $option.data("selected-time") || 0
                            });
                        }
                    });
                    selectionOrder.sort((a, b) => a.timestamp - b.timestamp);
                    return selectionOrder.map(opt => opt.value);
                } else {
                    // 原始顺序获取值
                    $checked.each(function () {
                        selectedValues.push(
                            $(this).closest(".multiselect-option").data("value")
                        );
                    });
                    return selectedValues;
                }
            });

            $container.data("updateOptionDisabled", function (value, disabled) {
                $dropdown
                    .find('.multiselect-option[data-value="' + value + '"]')
                    .toggleClass("disabled", disabled)
                    .find(".multiselect-checkbox")
                    .prop("disabled", disabled);
            });

            $container.data("updateOptions", function (newOptions, newSelected = []) {
                // 清空现有选项
                $dropdown.empty();

                // 更新设置
                settings.options = newOptions;
                settings.selected = newSelected;

                // 重新初始化选项（保持newSelected顺序）
                newSelected.forEach(value => {
                    const option = newOptions.find(opt => opt.value === value);
                    if (option) {
                        const isDisabled = option.disabled || false;
                        let dataAttributes = '';
                        if (option.data) {
                            for (const key in option.data) {
                                dataAttributes += ` data-${key}="${option.data[key]}"`;
                            }
                        }
                        const $option = $(`
                            <div class="multiselect-option" data-value="${option.value}"${dataAttributes}>
                                <label class="multiselect-label">
                                    <input type="checkbox" class="multiselect-checkbox" checked
                                        ${isDisabled ? "disabled" : ""}>
                                    <span class="multiselect-custom-checkbox"></span>
                                    ${option.text}
                                </label>
                            </div>
                        `);
                        if (isDisabled) {
                            $option.addClass("disabled");
                        }
                        $dropdown.append($option);
                    }
                });

                // 添加未选中的选项
                newOptions.forEach(option => {
                    if (!newSelected.includes(option.value)) {
                        const isDisabled = option.disabled || false;
                        let dataAttributes = '';
                        if (option.data) {
                            for (const key in option.data) {
                                dataAttributes += ` data-${key}="${option.data[key]}"`;
                            }
                        }
                        const $option = $(`
                            <div class="multiselect-option" data-value="${option.value}"${dataAttributes}>
                                <label class="multiselect-label">
                                    <input type="checkbox" class="multiselect-checkbox" 
                                        ${isDisabled ? "disabled" : ""}>
                                    <span class="multiselect-custom-checkbox"></span>
                                    ${option.text}
                                </label>
                            </div>
                        `);
                        if (isDisabled) {
                            $option.addClass("disabled");
                        }
                        $dropdown.append($option);
                    }
                });

                // 强制按newSelected顺序设置选中时间戳
                newSelected.forEach((value, index) => {
                    $dropdown.find(`.multiselect-option[data-value="${value}"]`)
                        .data("selected-time", index + 1);
                });

                updateSummary();
            });
            
            // 添加禁用方法
            $container.data("disable", function() {
                $container.addClass("disabled");
                $summary.addClass("disabled");
                // 如果下拉框是打开的，关闭它
                if (isOpen) {
                    isOpen = false;
                    $dropdown.hide();
                    $summary.removeClass("open");
                }
            });
            
            // 添加启用方法
            $container.data("enable", function() {
                $container.removeClass("disabled");
                $summary.removeClass("disabled");
            });
            
            // 添加获取禁用状态方法
            $container.data("isDisabled", function() {
                return $container.hasClass("disabled");
            });
        });
    };
})(jQuery);

// 使用示例
// $(document).ready(function() {
//     $('#myMultiselect').customMultiselect({
//         placeholder: '请选择',
//         options: [
//             { value: '1', text: '可选项1' },
//             { value: '2', text: '禁用项', disabled: true },
//             { value: '3', text: '可选项2' }
//         ],
//         selected: ['1']
//     });
// });
